package com.smforj.ssm.modules.lib.service.impl;

import java.util.ArrayList;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import com.smforj.ssm.frame.core.bean.SysCache;
import com.smforj.ssm.frame.core.socket.SocketService;
import com.smforj.ssm.mina.client.SocketClient;
import com.smforj.ssm.modules.lib.constant.LibType;
import com.smforj.ssm.modules.lib.domain.CheckInResponse;
import com.smforj.ssm.modules.lib.domain.CheckOutResponse;
import com.smforj.ssm.modules.lib.domain.FeePaidResponse;
import com.smforj.ssm.modules.lib.domain.ItemResponse;
import com.smforj.ssm.modules.lib.domain.LibraryRequest;
import com.smforj.ssm.modules.lib.domain.PatronResponse;
import com.smforj.ssm.modules.lib.domain.RFIDRequest;
import com.smforj.ssm.modules.lib.domain.Tag;
import com.smforj.ssm.modules.lib.service.SimpleLibraryService;
import com.smforj.ssm.modules.sys.util.ISip2Msg;
import com.smforj.ssm.modules.sys.util.MsgUtil;
import com.smforj.ssm.modules.sys.util.UtilFactory;
import com.smforj.ssm.util.PropKit;

/***
 * 图书管理系统接口实现类
 * 该类实现了独立的与图书管理软件对接功能,主要使用于不添加智能管理软件的情况,支持SIP2协议
 * 该对象采用Socket通讯,根据不同SIP2版本进行通讯
 *
 * @author Haijun Gao 
 * @date 2016-8-6 上午11:20:43
 * @desp http://www.cnblogs.com/saga5998/
 * @email 573107773@qq.com
 */
@Service("libraryService")
public class SimpleLibraryServiceImpl implements SimpleLibraryService  {
	/****
	 * 日志
	 */
    private Logger log = LoggerFactory.getLogger(this.getClass());


    private SocketService socketService = SysCache.getSocketService();

    private String charset = "UTF-8";

    /***
     * 获取sip2类型
     * @param itype
     * @return
     * @date 2017-4-28 下午2:55:47
     */
    private ISip2Msg getSip2Msg(Integer itype) {
        ISip2Msg msg = null;
        switch (itype) {
            case 1:
                msg = UtilFactory.getSip2(LibType.GDLISNET);
                break;
            case 2:
                msg = UtilFactory.getSip2(LibType.BEIDAQINGYANG);//北大清样
                break;
            case 3:
                msg = UtilFactory.getSip2(LibType.ES);//中科嘉禾
                break;
            default:
                msg = UtilFactory.getSip2(LibType.GDLISNET);
                break;
        }
        return msg;
    }

    /***
     * 登陆 图书管理系统
     * @param request 请求信息 包含图书信息，读者信息
     * @return 成功 message 为 User 失败 message 为 error message
     * @date 2016-8-3 下午2:24:56
     */
    @Override
    public PatronResponse getReader(LibraryRequest<String> request) {
        try {
            ISip2Msg msg = getSip2Msg(PropKit.getInt("LibType"));
            return msg.parseReaderInfo(
                    excuse( msg.readerInfoMsg(request.getSzUserId(), request.getSzUserPWD())));
        } catch (Exception ex) {
            log.error("查询读者信息异常：" + ex.getMessage());
            PatronResponse response = new PatronResponse();
            response.setStatus(-1);
            response.setMessage("业务异常");
            return response;
        }
    }

    /***
     * 查询图书信息
     * @param request 请求信息 包含图书id或Barcode
     * @return 成功 message 为 图书信息 失败 message 为 error message
     * @date 2016-11-1 下午3:22:27
     */
    @Override
    public ItemResponse getBookInfo(LibraryRequest<String> request) {
        try {
            ISip2Msg msg = getSip2Msg(PropKit.getInt("LibType"));
            return msg.parseBookInfo(
                    excuse( msg.bookInfoMsg(request.getData())));
        } catch (Exception ex) {
            log.error("查询图书信息异常：" + ex.getMessage());
            ItemResponse response = new ItemResponse();
            response.setStatus(-1);
            response.setMessage("业务异常");
            return response;
        }
    }

    /***
     * 执行
     * @param request
     * @param sendMsg
     * @return
     * @date 2016-8-6 上午11:34:50
     */
    private String excuse(String sendMsg) {
        //System.out.println(request.getSysConfig().getSip2ip() + " " + request.getSysConfig().getSip2port());
        SocketClient client = SocketClient.connect(PropKit.get("Sip2ip"), PropKit.getInt("Sip2port"));
        client.setCharset(charset);
        return client.sendAndRead(sendMsg);
    }

    /***
     * 借阅图书
     * @param request 请求信息 包含图书信息，读者信息
     *   必须字段 readerid,bookid
     *   可行字段 pwd
     * @return 成功 message 为 更新后的book 失败 message 为 error message
     * @date 2016-8-3 下午3:01:16
     */
    @Override
    public List<CheckOutResponse> doCheckout(LibraryRequest<String[]> request) {
        List<CheckOutResponse> list = new ArrayList<CheckOutResponse>();
        try { 
            for (String book : request.getData()) {
                ISip2Msg msg = getSip2Msg(PropKit.getInt("LibType"));
                CheckOutResponse response = msg.parseBorrow(excuse(
                        msg.borrowMsg(request.getSzUserId(), request.getSzUserPWD(), book)));
                if (response.getStatus() != 1) {
                    //图书已经外借 图书不存在 表示已经成功
                    if (response.getMessage().equalsIgnoreCase(MsgUtil.get("tsywj"))
                            || response.getMessage().equalsIgnoreCase(MsgUtil.get("tsbcz"))) {
                        response.setStatus(1);
                        response.setMessage(MsgUtil.get("jscg"));
                    }
                }
                list.add(response);
            }

        } catch (Exception ex) {
            log.error("执行借阅业务异常：" + ex.getMessage());
        }
        return list;
    }

    /***
     * 归还图书
     * @param request 请求信息 包含图书信息，读者信息
     * @return 成功 message 为 更新后的book 失败 message 为 error message
     * @date 2016-8-3 下午3:01:16
     */
    @Override
    public List<CheckInResponse> doCheckin(LibraryRequest<String[]> request) {
        List<CheckInResponse> list = new ArrayList<CheckInResponse>();
        try {
            for (String book : request.getData()) {
                ISip2Msg msg = getSip2Msg(PropKit.getInt("LibType"));
                CheckInResponse response = msg.parseReturn(excuse(
                        msg.returnMsg(book)));
                if (response.getStatus() != 1) {
                    //本书没有外借 //图书不存在 表示已经成功
                    if (response.getMessage().equalsIgnoreCase(MsgUtil.get("mywg"))
                            || response.getMessage().equalsIgnoreCase(MsgUtil.get("tsbcz"))) {
                        response.setStatus(1);
                        response.setMessage(MsgUtil.get("hscg"));
                    }
                }
                list.add(response);
            }
        } catch (Exception ex) {
            log.error("执行还书业务异常：" + ex.getCause().getMessage());
        }
        return list;
    }

    /***
     * 续借图书
     * @param request 请求信息 包含图书信息，读者信息
     * @return 成功 message 为 更新后的book 失败 message 为 error message
     * @date 2016-8-3 下午3:01:16
     */
    @Override
    public List<CheckOutResponse> doRenew(LibraryRequest<String[]> request) {
        List<CheckOutResponse> list = new ArrayList<CheckOutResponse>();
        //逻辑不正确
        try {
            for (String book : request.getData()) {
                ISip2Msg msg = getSip2Msg(PropKit.getInt("LibType"));
                CheckOutResponse response = msg.parseRenew(excuse(
                        msg.renewMsg(request.getSzUserId(), request.getSzUserPWD(), book)));
                if (response.getStatus() != 1) {
                    //图书已经外借 图书不存在 表示已经成功
                    if (response.getMessage().equalsIgnoreCase(MsgUtil.get("tsywj"))
                            || response.getMessage().equalsIgnoreCase(MsgUtil.get("tsbcz"))) {
                        response.setStatus(1);
                        response.setMessage(MsgUtil.get("jscg"));
                    }
                }
                list.add(response);
            }
        } catch (Exception ex) {
            log.error("执行续借业务异常：" + ex.getMessage());
        }
        return list;
    }

    /***
     * 登陆 图书管理系统
     * @param request 请求信息 读者信息
     * @return 成功 message 为 User 失败 message 为 error message
     * @date 2016-8-3 下午2:24:56
     */
    @Override
    public PatronResponse doLogin(LibraryRequest<String> request) {
        try {
            ISip2Msg msg = getSip2Msg(PropKit.getInt("LibType"));
            return msg.parseReaderInfo(
                    excuse( msg.loginMsg(request.getSzUserId(), request.getSzUserPWD())));
        } catch (Exception ex) {
            log.error("登陆信息异常：" + ex.getMessage());
            PatronResponse response = new PatronResponse();
            response.setStatus(-1);
            response.setMessage("业务异常");
            return response;
        }
    }

    @Override
    public String testStatus(String id) {
        return null;
    }

    @Override
    public List<ItemResponse> checkBookStatus(LibraryRequest<String[]> request) {
        return null;
    }

    @Override
    public FeePaidResponse doPayFee(LibraryRequest<String> request) {
        return null;
    }
 
	@Override
	public List<Tag> cBookStatus(RFIDRequest request) {
		// TODO Auto-generated method stub
		return null;
	}

}
